<template>
  <div>
      <el-dialog
        title="复制角色"
        :visible.sync="copyRoleDialogVisible"
        append-to-body
        @close="close()"
        top="1vh"
        width="80%">
        <el-row>
          <el-col :span="6">
            <el-tree ref='tree'
               :data="treeData"
               v-loading="loading"
               style="height: 400px; overflow: scroll"
               :props="defaultProps"
               :expand-on-click-node='false'
               @node-click="handleNodeClick"
               node-key="id"
               :highlight-current='true'
               :default-expand-all='true'>
                  <span class="custom-tree-node" slot-scope="{ node, data }">
                    <span v-if="data.other.Status == 0" class="ztrrName" style="display: inline-block;" :title="data.name">{{ data.name }}</span>
                    <span v-if="data.other.Status == 1" class="ztrrName" style="display: inline-block;color:red" :title="data.name">{{ data.name }}(禁用)</span>
                    <div style="display: inline-block;" class="treeNone">
                    </div>
                   </span>
               </el-tree>
          </el-col>
          <el-col :span="18">
            <div style="margin-top:15px;">
              <div class="select-container">
                <el-row class="">
                  <el-col :span="24" class="">
                    <el-form ref="form" label-width="100px" label-position='right' size="small" :inline="true">
                      <el-col :span="5" >
                        <el-form-item label="" style="margin:12px 5px;">
                          <el-input placeholder="登录名称" prefix-icon="el-icon-search" v-model="listQueryDemo.condition.loginName.value" clearable>
                          </el-input>
                        </el-form-item>
                      </el-col>
                      <el-col :span="5" >
                        <el-form-item label="" style="margin:12px 3px;">
                          <el-input placeholder="用户名称" prefix-icon="el-icon-search" v-model="listQueryDemo.condition.name.value" clearable>
                          </el-input>
                        </el-form-item>
                      </el-col>
                      <el-col :span="6">
                        <!--  -->
                        <el-form-item label="" style="margin:12px 0px;">
                          <el-select placeholder="请选择用户状态"  v-model="listQueryDemo.condition.status.value" clearable>
                            <el-option v-for="item in statusOptions" :key="item.key" :label="item.display_name" :value="item.key">
                            </el-option>
                          </el-select>
                        </el-form-item>
                      </el-col>
                      <el-col :span="8" style="padding-left:10px;margin-top:12px;float:right;margin-right:0">
                        <el-button size="small" style="height:30px;padding-top:0px;line-height:30px;" type="success" icon="el-icon-edit" @click="getList(selectOuinfoId,'find')">查 询</el-button>
                        <el-button size="small" style="height:30px;padding-top:0px;line-height:30px;" type="danger" icon="el-icon-circle-close-outline" @click="handleResetOrg">重 置</el-button>
                      </el-col>
                    </el-form>
                  </el-col>
                </el-row>
              </div>
            </div>
            <el-table
              :data="userDataDemo"
              size="small"
              @select-all="selectionOrgChange"
              @select="selectionOrgChange"
              height="330px"
              style="width: 100%;overflow: auto;border:#eeeeee">
              <el-table-column
                type="selection"
                width="30" align="center" >
              </el-table-column>
              <el-table-column type="index" label="序号" width="50" align="center">
                <template slot-scope="scope">
                <span>{{scope.$index + (serialNumberOrg - 1) * listQueryDemo.rowBounds.limit + 1}}</span>
                </template>
              </el-table-column>
              <el-table-column align="center" label="登录名" width="120" prop="loginName">
                <template slot-scope="scope">
                  <span>{{scope.row.loginName}}</span>
                </template>
              </el-table-column>
              <el-table-column align="center" label="用户名" width="120" prop="name">
                <template slot-scope="scope">
                  <span>{{scope.row.name}}</span>
                </template>
              </el-table-column>
              <el-table-column align="center" label="机构名称" width="200" prop="orgName">
                <template slot-scope="scope">
                  <span>{{scope.row.orgName}}</span>
                </template>
              </el-table-column>
              <el-table-column align="center" v-if="copyUserRoleData.isPt == 1" label="兼职部门" width="200" prop="compoundOrgname">
                <template slot-scope="scope">
                  <span>{{scope.row.compoundOrgname}}</span>
                </template>
              </el-table-column>
              <el-table-column align="center" label="状态" prop="status">
                <template slot-scope="scope">
                  <span>{{scope.row.status | statusFilter}}</span>
                </template>
              </el-table-column>
              <el-table-column align="center" label="允许访问开始/结束时间" width="180" prop="accessStartDate">
                <template slot-scope="scope">
                  <span>{{scope.row.accessStartDate}}</span>&#10;<span>{{scope.row.accessEndDate}}</span>
                </template>
              </el-table-column>
              <el-table-column align="center" label="职务" prop="postStatus">
                <template slot-scope="scope">
                  <span>{{jobfilter(scope.row.postStatus)}}</span>
                </template>
              </el-table-column>
            </el-table>
            <div class="pagination-container">
              <el-pagination background @size-change="handleSizeChangeDemo"
                             @current-change="handleCurrentChangeDemo"
                             :page-sizes="[10,20,30, 50]"
                             :page-size="listQueryDemo.rowBounds.limit"
                             layout="total, sizes, prev, pager, next, jumper"
                             :total="totalDemo">
              </el-pagination>
            </div>
          </el-col>
        </el-row>
        <el-row>
          <el-col align="right">
            <el-button size="small" @click="insertOrgList('insert')" type="primary">保存</el-button>
            <el-button size="small" @click="close()" type="primary">关 闭</el-button>
          </el-col>
        </el-row>
    </el-dialog>
  </div>
</template>

<script>
import {
  batchCopyRoles,
  SysOrgInfo,
  treeById
} from '@/api/systemManage/roleManagementRoleEdit'
import {
  selectSysSubsys
} from '@/api/systemManage/roleManagement'
import { getOrgTree, compositeSelect}  from '@/api/systemManage/userManagement'
import { compositeSelect as compositeSelectPt} from '@/api/systemManage/partJobManagement'
import {
  statusOptions,
  statusKeyValue,
  ptOptions,
  ptKeyValue
} from '@/utils/allOptions'
export default {
  name: 'copyUserRole',
  props: ['copyUserRoleData'],
  components: {},
  data() {
    return {
      total: 0,
      treeData: [],
      editUserRoleOrgData: [],
      loading: false,
      copyRoleDialogVisible: false,
      subSystemsOptions: [],
      userDataDemo: [],
      postStatusOptions: [],
      statusOptions,
      ptOptions,
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      listQueryDemo: {
        rowBounds: {
          offset: 0,
          limit: 10
        },
        orgId: '',
        condition: {
          pt:{
            property: 'pt',
            value: '',
            type: 'EQ'
          },
          loginName:{
            property: 'loginName',
            value: '',
            type: 'LIKE'
          },
          name:{
            property: 'name',
            value: '',
            type: 'LIKE'
          },
          status: {
            property: 'status',
            value: '0',
            type: 'EQ'
          }
        },
        sort: [{
          direction: 'ASC',
          property: 'orderNo'
        }]
      },
      totalDemo: 0,
      form: '',
      userData: [],
      unTotal: 0,
      unUserData: [],
      checkedUsersSeted: [],
      checkedOrgUsers: [],
      serialNumberOrg: 1,
      selectOuinfoId: null
    }
  },
  // 画面刚进入method
  mounted() {
    this.editSubSystemsOptions()
  },
  created() {
    this.getTree()
    this.GetCodeList()
  },
  filters: {
    statusFilter(target) {
      return statusKeyValue[target]
    },
    ptFilter(target) {
      return ptKeyValue[target]
    }
  },
  computed: {
    jobfilter() {
      return function(index) {
        if (index !== null && index !== '') {
          return this.postStatusOptions[index].codeName
        }
      }
    }
  },
  methods: {
    GetCodeList() {
      let args = {}
      args.codeType = 'JOB_TYPE_CATEGORY_CODE'
      args.codeStatus = '0'

      this.$store.dispatch('SysCodeListByCodeType', args).then(res => {
        let data = res.data
        if (data && data.length > 0) {
          data.forEach((item, i) => {
            item.id = JSON.stringify({
              'id': item.codeKey,
              'name': item.codeName
            })
          })
        }
        this.postStatusOptions = data
        this.loading = false
      }).catch((err) => {
        console.log(err)
      })
    },
    // 翻页器使用(按组织机构添加人员)
    handleSizeChangeDemo(val) {
      this.listQueryDemo.rowBounds.limit = val
      this.listQueryDemo.rowBounds.offset = this.listQueryDemo.rowBounds.limit * (this.serialNumberOrg - 1)
      this.getList(this.selectOuinfoId)
    },
    // 翻页器使用(按组织机构添加人员)
    handleCurrentChangeDemo(val) {
        this.serialNumberOrg = val
        this.listQueryDemo.rowBounds.offset =
        this.listQueryDemo.rowBounds.limit * (val - 1)
        this.getList(this.selectOuinfoId)
    },
     selectionOrgChange(val,row) {
       this.checkedOrgUsers=[];
       if(val){
         for(var i in val){
             for(var j in this.copyUserRoleData.roles){
               var tempUserRoleOrg = {
                 roleId: '',
                 userId: '',
                 orgId: ''
               }
                tempUserRoleOrg.roleId = this.copyUserRoleData.roles[j]
                tempUserRoleOrg.userId = val[i].id
                if (this.copyUserRoleData.isPt) {
                  tempUserRoleOrg.orgId = val[i].compoundOrgId
                } else {
                  tempUserRoleOrg.orgId = val[i].orgId
                }
                this.checkedOrgUsers.push(tempUserRoleOrg)
             }
         }
       }
     },
    getTree() {
      this.copyRoleDialogVisible = true
      if (this.copyUserRoleData.isPt) {
        getOrgTree({ id: this.$store.getters.rootOrgId }).then(response => {
          this.treeData = response.data.data
          if (this.$store.state.user.selectCopyRoleOrgIdByOrgPt) {
              this.$nextTick(() => {
                this.$refs.tree.setCurrentKey(this.$store.state.user.selectCopyRoleOrgIdByOrgPt) // treeBox 元素的ref   value 绑定的node-key
              })
              this.selectOuinfoId = this.$store.state.user.selectCopyRoleOrgIdByOrgPt
           } else {
              this.$nextTick(() => {
                this.$refs.tree.setCurrentKey(this.$store.getters.orgId) // treeBox 元素的ref   value 绑定的node-key
              })
              this.selectOuinfoId = this.$store.getters.orgId
           }
           this.listQueryDemo.orgId = this.selectOuinfoId
           this.getList(this.selectOuinfoId)
        })
      } else {
        getOrgTree({ id: this.$store.getters.rootOrgId }).then(response => {
          this.treeData = response.data.data
          if (this.$store.state.user.selectCopyRoleOrgIdByOrg) {
              this.$nextTick(() => {
                this.$refs.tree.setCurrentKey(this.$store.state.user.selectCopyRoleOrgIdByOrg) // treeBox 元素的ref   value 绑定的node-key
              })
              this.selectOuinfoId = this.$store.state.user.selectCopyRoleOrgIdByOrg
           } else {
              this.$nextTick(() => {
                this.$refs.tree.setCurrentKey(this.$store.getters.orgId) // treeBox 元素的ref   value 绑定的node-key
              })
              this.selectOuinfoId = this.$store.getters.orgId
           }
           this.listQueryDemo.orgId = this.selectOuinfoId
           this.getList(this.selectOuinfoId)
        })
      }
    },

    getList(orgId,action) {
        if (orgId) {
          if (action == 'find') {
            this.checkedOrgUsers = [];
            this.listQueryDemo.rowBounds.offset = 0
            this.totalDemo = 0
            this.serialNumberOrg = 1
          }
          this.listQueryDemo.orgId = orgId
          if (this.copyUserRoleData.isPt) {
            this.listQueryDemo.condition.pt.value = 1
            compositeSelectPt(this.listQueryDemo).then(response => {
              this.userDataDemo = response.data.data.records
              this.totalDemo = response.data.data.count
              this.listLoading = false
            })
          } else {
            this.listQueryDemo.condition.pt.value = 0
            compositeSelect(this.listQueryDemo).then(response => {
              this.userDataDemo = response.data.data.records
              this.totalDemo = response.data.data.count
              this.listLoading = false
            })
          }
        } else {
          this.$message({
            message: '请选择组织机构。',
            type: 'warning'
          })
        }
    },
     insertOrgList(flag) {
      if (this.checkedOrgUsers.length > 0) {
         batchCopyRoles(this.checkedOrgUsers).then(response => {
           this.getList(this.selectOuinfoId)
           this.checkedOrgUsers=[];
          this.$message({
            message: '角色复制成功',
            type: 'success'
          })
         })
       } else {
          this.$message({
            message: '请选择人员',
            type: 'warning'
          })
       }
     },
    editSubSystemsOptions() {
      const query = {
        sort: [
          {
            direction: 'ASC',
            property: 'id'
          }
        ]
      }
      selectSysSubsys(query).then(response => {
        const records = response.data.data.records
        if (response.data.data.count > 0) {
          this.subSystemsOptions = []
          for (const item of records) {
            const input = {}
            input.id = item.id
            input.name = item.name
            this.subSystemsOptions.push(input)
          }
        }
      })
    },
   close() {
      this.$emit('changeCloseDialog')
   },
    handleNodeClick(data) {
      this.checkedOrgUsers=[];
      this.serialNumberOrg =1
      this.listQueryDemo.rowBounds.offset =0
      this.totalDemo =0
      this.selectOuinfoId = data.id
      if (this.copyUserRoleData.isPt) {
        this.$store.commit('SET_SELECTCOPYROLEORGID_BYORGID_PT', this.selectOuinfoId)
      } else {
        this.$store.commit('SET_SELECTCOPYROLEORGID_BYORGID', this.selectOuinfoId)
      }
      this.getList(this.selectOuinfoId)
    },
     handleResetOrg() {
       this.checkedOrgUsers=[];
       this.listQueryDemo.condition.loginName.value = ''
       this.listQueryDemo.condition.name.value = ''
       this.listQueryDemo.condition.status.value = '0'
       this.listQueryDemo.rowBounds.offset = 0
       this.listQueryDemo.rowBounds.limit = 10
       this.totalDemo = 0
       this.serialNumberOrg = 1
       this.getList(this.selectOuinfoId,'reset')
     }
  }
}
</script>

<style scoped>
.treeArea {
    max-height: 66vh;
    overflow-y: auto;
}
</style>
